#include "base/amscene.h"
#include "glrenderer.h"
#include "util/ammath.h"
#include "util/glutils.h"
#include <QMouseEvent>
#include <QKeyEvent>
#include <QMessageBox>
#include <iostream>

GLRenderer::GLRenderer(QWidget *parent) : QGLWidget(parent)
{
    startTimer(40);
    m_preMouseX = m_preMouseY = 0.0f;
    m_W = m_H = 400;
    m_PanKeyDown = false;
    setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
    setFocusPolicy(Qt::StrongFocus);
}

void GLRenderer::initializeGL()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0, 1.0, 0.1, 100.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glShadeModel(GL_SMOOTH);
}

void GLRenderer::resizeGL(int w, int h)
{
    m_W = w;
    m_H = h;
    glViewport(0, 0, w, h);
    float r = (float) w / (float) h;
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0, r, 0.1, 100.0);
    glTranslatef(0.0f, 0.0f, -8.0f);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void GLRenderer::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    AMScene::get()->render();
}

void GLRenderer::timerEvent(QTimerEvent *) {
    updateGL();
}

void GLRenderer::mouseMoveEvent(QMouseEvent * ev) {
    int dx = ev->x() - m_preMouseX;
    int dy = ev->y() - m_preMouseY;

    if((ev->buttons() & Qt::LeftButton) && m_PanKeyDown) {

    } else if (ev->buttons() & Qt::LeftButton) {

    }
    m_preMouseX = ev->x();
    m_preMouseY = ev->y();
}

void GLRenderer::mousePressEvent(QMouseEvent * ev) {
    if(ev->buttons() & Qt::LeftButton) {
        m_preMouseX = ev->x();
        m_preMouseY = ev->y();
    }
}

void GLRenderer::keyPressEvent(QKeyEvent * ev) {
    if(ev->key() == Qt::Key_Control) {
        m_PanKeyDown = true;
    }
}

void GLRenderer::keyReleaseEvent(QKeyEvent * ev) {
    if(ev->key() == Qt::Key_Control) {
        m_PanKeyDown = false;
    }
}

QSize GLRenderer::minimumSizeHint() const
{
    return QSize(50, 50);
}

QSize GLRenderer::sizeHint() const
{
    return QSize(800, 600);
}
